'use client';

// 文件树组件
// REF: API-SHARE189-004@v1.0

import React, { useState } from 'react';
import {
  ChevronRight,
  ChevronDown,
  FolderOpen,
  FileText
} from 'lucide-react';

import { FileTreeProps, FileTreeNode } from './types';
import { formatBytes } from './utils';

export function FileTree({ nodes, level = 0 }: FileTreeProps) {
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());

  const toggleNode = (nodeId: string) => {
    const newExpanded = new Set(expandedNodes);
    if (newExpanded.has(nodeId)) {
      newExpanded.delete(nodeId);
    } else {
      newExpanded.add(nodeId);
    }
    setExpandedNodes(newExpanded);
  };

  return (
    <div className="space-y-1">
      {nodes.map((node) => {
        const isExpanded = expandedNodes.has(node.id);
        const hasChildren = node.children && node.children.length > 0;
        
        return (
          <div key={node.id}>
            <div 
              className="flex items-center gap-2 py-1 px-2 hover:bg-gray-50 rounded cursor-pointer"
              style={{ paddingLeft: `${level * 20 + 8}px` }}
              onClick={() => hasChildren && toggleNode(node.id)}
            >
              {hasChildren ? (
                isExpanded ? (
                  <ChevronDown className="h-4 w-4 text-gray-500" />
                ) : (
                  <ChevronRight className="h-4 w-4 text-gray-500" />
                )
              ) : (
                <div className="w-4" />
              )}
              
              {node.isFolder ? (
                <FolderOpen className="h-4 w-4 text-blue-500" />
              ) : (
                <FileText className="h-4 w-4 text-gray-500" />
              )}
              
              <span className="text-sm text-gray-700 flex-1">{node.name}</span>
              
              {!node.isFolder && (
                <span className="text-xs text-gray-500">{formatBytes(node.size)}</span>
              )}
            </div>
            
            {hasChildren && isExpanded && (
              <FileTree nodes={node.children!} level={level + 1} />
            )}
          </div>
        );
      })}
    </div>
  );
}

export default FileTree;